/**
 * @Title: LeaveOutActivity.java
 * @Package: com.jason.fingerprint.ui
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月9日 下午8:03:48
 * @Version: V1.0
 */
package com.jason.fingerprint.ui;

import java.util.ArrayList;
import java.util.List;

import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.ui.BindView;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.ui.activity.BaseActivity;
import org.kymjs.aframe.utils.StringUtils;
import org.kymjs.aframe.utils.SystemTool;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.fpi.MtRfid;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android_serialport_api.FingerprintManager;

import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.R;
import com.jason.fingerprint.adapter.LeaveOutAdapter;
import com.jason.fingerprint.beans.LeaveOutBean;
import com.jason.fingerprint.beans.ui.FingerPrintBean;
import com.jason.fingerprint.beans.ui.ImageOrAudioBean;
import com.jason.fingerprint.common.DataHelper;
import com.jason.fingerprint.common.DateFormat;
import com.jason.fingerprint.common.DialogHelper;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.logic.GetLeaveOutSyncLogic;
import com.jason.fingerprint.logic.MatchFingerprintSyncLogic;
import com.jason.fingerprint.logic.UpdateSignFlagSyncLogic;
import com.jason.fingerprint.logic.UploadToTempSyncLogic;
import com.jason.fingerprint.utils.DataUtils;
import com.jason.fingerprint.widget.LoadingDialog;

/**
 * @ClassName: LeaveOutActivity
 * @Description: 外出请假
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月9日 下午8:03:48
 */
@SuppressLint("HandlerLeak")
public class LeaveOutActivity extends BaseActivity implements
		OnItemClickListener {

	private static final String TAG = "LeaveOutActivity";
	public static final int CHOOSE_PHOTO_REQUEST_OK = 1001;
	private static final int mChooseImageCount = 1;
	private static final long FINGER_AGAIN_TIME = 1500L;

	@BindView(id = R.id.header_back, click = true)
	private Button mBackButton;
	@BindView(id = R.id.header_title)
	private TextView mTitleTextView;
	@BindView(id = R.id.leave_out_listview)
	private ListView mListView;
	@BindView(id = R.id.leave_out_button_select, click = true)
	private Button mSelectButton;
	@BindView(id = R.id.leave_out_button_upload, click = true)
	private Button mUploadButton;

	@BindView(id = R.id.leave_out_button_ask_leave, click = true)
	private Button mAskButton;
	@BindView(id = R.id.leave_out_button_sick_leave, click = true)
	private Button mSickButton;

	private AppContext mAppContext;
	private KJDB mKjdb;
	private LeaveOutAdapter mLeaveOutAdapter;
	private List<LeaveOutBean> mLeaveOutBeans;

	private Context mContext;
	private int mSignType = 1;// 默认请假签到
	private LoadingDialog mProgressDialog;

	private MatchFingerprintSyncLogic mLogic;
	private LeaveOutBean mLeaveOutBean;
	private List<String> mCacheCheckImages = new ArrayList<String>();

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.I_KJActivity#setRootView()
	 */
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_leave_out);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initWidget()
	 */
	@Override
	protected void initWidget() {
		// TODO Auto-generated method stub
		super.initWidget();
		mLeaveOutAdapter = new LeaveOutAdapter(this);
		mListView.setAdapter(mLeaveOutAdapter);
		mListView.setOnItemClickListener(this);

		mContext = this;
		mAppContext = (AppContext) getApplication();
		mKjdb = mAppContext.getKjdb();
		mProgressDialog = new LoadingDialog(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initData()
	 */
	@Override
	protected void initData() {
		super.initData();
		mTitleTextView.setText("外出请假");
		mAppContext = (AppContext) getApplication();
		mKjdb = mAppContext.getKjdb();
		if (SystemTool.checkNet(LeaveOutActivity.this)) {
			// TODO 放在线程中
			GetLeaveOutSyncLogic logic = new GetLeaveOutSyncLogic(
					mAppContext, mLeaveOutHandle, true);
			logic.execute();
		} else {
			Toast.makeText(LeaveOutActivity.this, "请检查网络",
					Toast.LENGTH_SHORT).show();
		}
		initFinger();
	}
	
	// 初始化指纹信息
	private void initFinger() {
		MtRfid.getInstance().RfidInit();
		MtRfid.getInstance().SetContext(this);
		mLogic = MatchFingerprintSyncLogic.getInstance();
		mLogic.setFingerPrintReader(FingerprintManager.getInstance()
				.getNewAsyncFingerprint());
		mLogic.setHandle(mFingerpringHandler);
		mLogic.isManager(false);
	}

	// 指纹验证
	private void matchFingerPrint() {
		mProgressDialog.setMessage("请按指纹...");
		mProgressDialog.show();
		mLogic.execute();
		mProgressDialog.setMatchLogic(mLogic);
	}

	// 指纹验证结果回调
	private Handler mMatchHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
			}
			if (mLogic != null) {
				mLogic.destory();
			}
			new Handler().postDelayed(mFingerAgainRunnable, FINGER_AGAIN_TIME);
			switch (msg.what) {
			case 100:
				// 匹配成功
				int pageId = msg.arg1;
				saveData(pageId);
				break;
			case 101:
				// 匹配失败
				Toast.makeText(mContext, "没有找到匹配的指纹", Toast.LENGTH_SHORT)
						.show();
				break;

			default:
				break;
			}
		};
	};
	
	private Runnable mFingerAgainRunnable = new Runnable() {

		@Override
		public void run() {
			matchFingerPrint();
		}

	};

	private Handler mFingerpringHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Message message = new Message();
			switch (msg.what) {
			case UIHelper.FINGERPRINT_UPCHAR_SUCCESS:
				break;
			case UIHelper.FINGERPRINT_UPCHAR_FAIL:// char--返回失败
			case UIHelper.FINGERPRINT_REGMODE_FAIL:// char--模板合成失败
			case UIHelper.FINGERPRINT_GENCHAR_FAIL:// char--生成特征值失败
			case UIHelper.FINGERPRINT_DELETECHAR_FAIL:// char--模板下载失败
			case UIHelper.FINGERPRINT_UPIMAGE_FAIL:// image--生成失败
			case UIHelper.FINGERPRINT_SEARCH_FAIL:
				message.what = 101;
				mMatchHandler.handleMessage(message);
				break;
			case UIHelper.FINGERPRINT_SEARCH_SUCCESS:
				// 匹配成功
				int pageId = msg.arg1;
				message.what = 100;
				message.arg1 = pageId;
				mMatchHandler.handleMessage(message);
				break;
			case UIHelper.FINGERPRINT_AGAIN:// 再次按手指
				mProgressDialog.setMessage("请再次按指纹...");
				mProgressDialog.show();
			case UIHelper.FINGERPRINT_ONMATCH_SUCCESS:// image--图片合成成功

				break;

			default:
				break;
			}
		};

	};

	// 调用接口回调
	private Handler mLeaveOutHandle = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case 0:
				// 成功，有数据返回
				mLeaveOutBeans = (List<LeaveOutBean>) msg.obj;
				mLeaveOutAdapter.addAll(mLeaveOutBeans);
				break;
			case 1:
				// mValidateFingerprint.FP_Search(1, 0, 999);
				// matchFingerPrint();
				break;
			default:
				Toast.makeText(getApplicationContext(), "没有数据返回",
						Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.kymjs.aframe.ui.activity.KJFrameActivity#widgetClick(android.view
	 * .View)
	 */
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.header_back:
			MtRfid.getInstance().RfidClose();	//Close
			FingerprintManager.getInstance().closeSerialPort();
			KJActivityManager.create().finishActivity(this);
			break;
		case R.id.leave_out_button_select:
			showActivity(this, LeaveOutRecordActivity.class);

			break;
		case R.id.leave_out_button_upload:
			uploadLeaveOutInfo();
			break;
		case R.id.leave_out_button_ask_leave:
			mSignType = 1;
			matchFingerPrint();
			break;
		case R.id.leave_out_button_sick_leave:
			mSignType = 3;
			matchFingerPrint();
			break;

		default:
			break;
		}
	}

	// 上传记录
	private void uploadLeaveOutInfo() {
		if (SystemTool.checkNet(this)) {
			mProgressDialog.setMessage("请稍等，签到记录正在上传中...");
			mProgressDialog.show();
			UpdateSignFlagSyncLogic logic = new UpdateSignFlagSyncLogic(
					mAppContext, mUploadHander, true);
			logic.execute();
		} else {
			Toast.makeText(this, "请检查网络", Toast.LENGTH_SHORT).show();
		}
	}

	// 文件上传
	private void uploadFile() {
		if (SystemTool.checkNet(this)) {

			UploadToTempSyncLogic logic = new UploadToTempSyncLogic(
					mAppContext, mUploadHander, true, 5);
			logic.execute();
		}
	}

	private Handler mUploadHander = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UIHelper.FILE_UPLOAD_FAIL:
			case UIHelper.LEAVEOUT_UPLOAD_FAIL:
				if (mProgressDialog != null) {
					mProgressDialog.dismiss();
				}
				Toast.makeText(mContext, "记录上传失败，请重试", Toast.LENGTH_SHORT)
						.show();
				break;
			case UIHelper.LEAVEOUT_UPLOAD_SUCCESS:
				// 上传文件
				uploadFile();
				break;
			case UIHelper.FILE_UPLOAD_SUCCESS:
				if (mProgressDialog != null) {
					mProgressDialog.dismiss();
				}
				Toast.makeText(mContext, "记录上传成功", Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
		};
	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget
	 * .AdapterView, android.view.View, int, long)
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		LeaveOutBean bean = (LeaveOutBean) parent.getItemAtPosition(position);
		// TODO 跳转到详情页面
		Intent intent = new Intent(LeaveOutActivity.this,
				LeaveOutDetailActivity.class);
		intent.putExtra("LeaveOutBean", bean);
		startActivity(intent);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.i(TAG, "---> onActivityResult requestCode:" + requestCode
				+ ",resultCode:" + resultCode);
		if (requestCode == CHOOSE_PHOTO_REQUEST_OK && resultCode == 1001) {
			saveLeaveOutDate();
			if (data != null) {
				mCacheCheckImages = data
						.getStringArrayListExtra("mCacheCheckImages");
				// 保存图片到数据库
				if (mCacheCheckImages != null && !mCacheCheckImages.isEmpty()) {
					String path = mCacheCheckImages.get(0);
					Message message = new Message();
					message.what = 100;
					message.obj = path;
					savePhoto(path);
				}

			}
		}
	}

	// 请求成功之后保存数据
	private void saveData(final int pageId) {
		List<FingerPrintBean> beans = mKjdb.findAllByWhere(
				FingerPrintBean.class, " id = " + pageId);
		if (beans != null && !beans.isEmpty()) {
			FingerPrintBean bean = beans.get(0);
			if (bean != null) {
				String userId = bean.getUserId();// 获取当前矫正人员的id

				mLeaveOutBean = getMatchLeaveOutBean(userId);
				if (mLeaveOutBean == null) {
					Toast.makeText(mContext, "没有找匹配的数据，请先申请请销假", Toast.LENGTH_SHORT).show();
					return;
				}
				// TODO 从数据库中查询该用户是否存在，如果存在则表示已经签到过了，提示用户已经操作过了
				boolean flag = isSuccessSign(mLeaveOutBean.getId(), mSignType);
				if (!flag) {
					takePhoto();
				}
				if (!flag) {
					// 还没有签到过，把此数据存入数据库
					LeaveOutBean outBean = getOutBeanById(userId);
					if (outBean != null) {
						LeaveOutBean bean2 = new LeaveOutBean();
						bean2.setId(outBean.getId());
						bean2.setTime(DataUtils.converDatLongToString(
								System.currentTimeMillis(),
								DateFormat.DATE_YMD_HMS));
						bean2.setSignFlag("1");
						bean2.setRymcid(outBean.getRymcid());
						bean2.setName(outBean.getName());
						bean2.setPhotoUrl(outBean.getPhotoUrl());
						bean2.setSignType(String.valueOf(mSignType));
						bean2.setIsCancel(outBean.getIsCancel());
						bean2.setIsCancelLeave(outBean.getIsCancelLeave());
						bean2.setLeaveId(outBean.getLeaveId());
						bean2.setOrganid(outBean.getOrganid());
						bean2.setOrgan(outBean.getOrgan());
						// TODO 保存成功之后需要提示是否拍照
						mKjdb.save(bean2);
					}
				}
			}
		}

	}

	private void takePhoto() {
		// 拍照
		new AlertDialog.Builder(this)
				.setTitle("拍照")
				.setMessage("是否进行拍照？")
				.setCancelable(true)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						Intent takePicture = new Intent(LeaveOutActivity.this,
								ChoosePhotoActivity.class);
						takePicture.putExtra(
								ChoosePhotoActivity.CHOOSE_PHOTO_COUNT,
								mChooseImageCount);
						startActivityForResult(takePicture,
								DialogHelper.CHOOSE_PHOTO_REQUEST_OK);
					}

				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						saveLeaveOutDate();
						dialog.dismiss();
					}

				}).create().show();

	}

	private void saveLeaveOutDate() {
		if (mLeaveOutBean != null) {
			LeaveOutBean bean2 = new LeaveOutBean();
			bean2.setId(mLeaveOutBean.getId());
			bean2.setTime(DataUtils.converDatLongToString(
					System.currentTimeMillis(), DateFormat.DATE_YMD_HMS));
			bean2.setSignFlag("1");
			bean2.setRymcid(mLeaveOutBean.getRymcid());
			bean2.setName(mLeaveOutBean.getName());
			bean2.setPhotoUrl(mLeaveOutBean.getPhotoUrl());
			bean2.setSignType(String.valueOf(mSignType));
			bean2.setIsCancel(mLeaveOutBean.getIsCancel());
			bean2.setIsCancelLeave(mLeaveOutBean.getIsCancelLeave());
			bean2.setLeaveId(mLeaveOutBean.getLeaveId());
			bean2.setOrganid(mLeaveOutBean.getOrganid());
			bean2.setOrgan(mLeaveOutBean.getOrgan());
			// TODO 保存成功之后需要提示是否拍照
			mKjdb.save(bean2);
			String tip = "请假签到成功";
			if (mSignType != 1) {
				tip = "销假签到成功";
			}
			Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, "签到失败", Toast.LENGTH_SHORT).show();
		}
	}

	private LeaveOutBean getOutBeanById(String id) {

		if (mLeaveOutBeans != null && !mLeaveOutBeans.isEmpty()) {
			int size = mLeaveOutBeans.size();
			for (int i = 0; i < size; i++) {
				LeaveOutBean bean = mLeaveOutBeans.get(i);
				if (bean != null && bean.getRymcid().equals(id)) {
					return bean;
				}
			}
		}
		return null;
	}

	// 判断是否签到过
	private boolean isSuccessSign(String id, int signType) {
		try {
			List<LeaveOutBean> beans = mKjdb.findAllByWhere(LeaveOutBean.class,
					" signType = '" + signType + "' and id = '" + id + "'");
			if (beans != null && !beans.isEmpty()) {
				LeaveOutBean bean = beans.get(0);
				if (bean != null) {
					String toast = "";
					if (signType == 1) {
						toast = "已经请假签到";
					} else if (signType == 3) {
						toast = "已经销假签到";
					}
					Toast.makeText(this, toast, Toast.LENGTH_SHORT).show();
					return true;

				}
			}
		} catch (Exception e) {
			return false;
		}
		return false;
	}

	// 获取匹配的请销假信息
	private LeaveOutBean getMatchLeaveOutBean(String userId) {
		if (mLeaveOutBeans != null && !mLeaveOutBeans.isEmpty()) {
			for (int i = 0; i < mLeaveOutBeans.size(); i++) {
				LeaveOutBean leaveOutBean = mLeaveOutBeans.get(i);
				String rymcId = leaveOutBean.getRymcid();
				if (!StringUtils.isEmpty(userId)
						&& !StringUtils.isEmpty(rymcId)
						&& rymcId.equals(userId)) {
					return leaveOutBean;
				}
			}
		}
		return null;
	}

	// 把选取的图片保存到数据库
	private void savePhoto(String photoPath) {
		Log.i(TAG, "---> savePhoto photoPath:" + photoPath);
		Log.i(TAG, "---> savePhoto :" + mLeaveOutBean);
		if (!StringUtils.isEmpty(photoPath)) {
			ImageOrAudioBean bean = DataHelper.getImageOrAudioBeanInfoByPath(
					this, photoPath, 1);
			bean.setServiceId(5);
			bean.setSignType(String.valueOf(mSignType));
			bean.setParentId(mLeaveOutBean.getId());
			Log.i(TAG, "---> savePhoto " + bean);
			mKjdb.save(bean);
		} else {
			Toast.makeText(this, "选取图片失败", Toast.LENGTH_SHORT).show();
		}
	}
	
	/* (non-Javadoc)
	 * @see org.kymjs.aframe.ui.activity.BaseActivity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		KJActivityManager.create().finishActivity(this);
		super.onDestroy();
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onBackPressed()
	 */
	@Override
	public void onBackPressed() {
		KJActivityManager.create().finishActivity(this);
		super.onBackPressed();
	}
	
	@Override
	protected void onStop() {
		if (mLogic != null) {
			mLogic.destory();
		}
		MtRfid.getInstance().RfidClose(); // Close
		super.onStop();
	}

}
